package com.example.shop.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shop.common.api.ServiceReturn;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.mapper.MerchantMapper;
import com.example.shop.pojo.Merchant;
import com.example.shop.pojo.User;
import com.example.shop.rabbitmq.component.MerchantMessageComponent;
import com.example.shop.rabbitmq.dto.ChatMessage;
import com.example.shop.user.service.ChatService;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    MerchantMapper merchantMapper;

    @Override
    public ServiceReturn<Boolean> send(User user, ChatMessage chatMessage) {
        //保证发送的用户是当前登录的用户
        if(!user.getUserId().equals(chatMessage.getUserId())){
            return new ServiceReturn(ServiceStateCode.No_PERMISSION_TO_SEND,false);
        }
        //校验该商家是否存在
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id",chatMessage.getMerchantId());
        boolean exists = merchantMapper.exists(queryWrapper);
        if(!exists){
            return new ServiceReturn(ServiceStateCode.NO_EXIST_MERCHANT,false);
        }
        //消息发送前的消息处理
        MessagePostProcessor messagePostProcessor=(msg)->{
            MessageProperties messageProperties = msg.getMessageProperties();
            //设置消息类型，默认application/octet-stream
            //设置为json字符串类型
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            return msg;
        };
        //发送给商家的交换机，路由键因为为商家id。因为是用户发送消息给商家，所以商家是接受者
        String routing = String.valueOf(chatMessage.getMerchantId());
        rabbitTemplate.convertAndSend(MerchantMessageComponent.MSG_EXCHANGE,routing,chatMessage,messagePostProcessor);
        return new ServiceReturn(ServiceStateCode.SUCCESS,true);
    }
}
